package net.roobook.cms.modules.admin.service;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.roobook.cms.common.constant.BaseConstant;
import net.roobook.cms.common.entity.SearchEntity;
import net.roobook.cms.common.service.CrudService;
import net.roobook.cms.modules.admin.dao.MenuMapper;
import net.roobook.cms.modules.admin.dao.RoleMapper;
import net.roobook.cms.modules.admin.entity.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author cos
 * @email 327878610@qq.com
 * @link https://roobook.net
 * @Description 菜单Service
 * @date 2023/9/24 20:05
 **/
@Service
public class MenuService extends CrudService<MenuMapper,Menu> {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RoleMapper roleMapper;
    public List<Menu> queryListByUserId(String userId) {
        List<Menu> menus;
        List<String> roles = roleMapper.selectRoleCodesByUserId(userId);
        if(roles.contains(BaseConstant.ADMIN_ROLE)) {
            menus = menuMapper.selectListByParentId("-1");
            menus = recursionGetMenus(menus);
        }else {
            menus = menuMapper.selectListByUserId(userId, "-1");
            menus = recursionGetMenus(userId, menus);
        }
        return menus;
    }

    public List<Menu> queryAll() {
        return menuMapper.selectAll();
    }


    public Menu queryMenuById(String id) {
        Menu menu = menuMapper.selectByPrimaryKey(id);
        if(StrUtil.isNotBlank(menu.getParentId()) && !"-1".equals(menu.getParentId())) {
            Menu parent = menuMapper.selectByPrimaryKey(menu.getParentId());
            menu.setParentMenuName(parent.getMenuName());
        }
        return menu;
    }

    /**
     * 根据用户ID递归获取所拥有的菜单权限
     * @param userId
     * @param menus
     * @return
     */
    private List<Menu> recursionGetMenus(String userId, List<Menu> menus) {
        for(int i = 0;i < menus.size();i++) {
            Menu menu = menus.get(i);
            List<Menu> children = menuMapper.selectListByUserId(userId, menu.getId());
            children = recursionGetMenus(userId, children);
            menu.setChildren(children);
        }
        return menus;
    }


    /**
     * 递归获取所有菜单权限
     * @param menus
     * @return
     */
    private List<Menu> recursionGetMenus(List<Menu> menus) {
        for(int i = 0;i < menus.size();i++) {
            Menu menu = menus.get(i);
            List<Menu> children = menuMapper.selectListByParentId(menu.getId());
            children = recursionGetMenus(children);
            menu.setChildren(children);
        }
        return menus;
    }

}
